package cn.xinfei.xdecision.datasource.mysql;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Slf4j
@Configuration
@ConditionalOnProperty("spring.datasource.druid.rcs.enable")
@MapperScan(sqlSessionFactoryRef = "rcsSqlSessionFactory", basePackages = {
        "cn.xinfei.xdecision.common.migrate"
})
public class RcsDbConfiguration {

    @Bean("rcsDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.rcs")
    public DataSource rcsDataSource() {
        log.info("初始化 rcsDataSource");
        return new DruidDataSource();
    }

    @Bean("rcsSqlSessionFactory")
    @ConditionalOnProperty("spring.datasource.druid.rcs.enable")
    public SqlSessionFactoryBean rcsSqlSessionFactory(@Qualifier("rcsDataSource") DataSource rcsDataSource,
                                                      ApplicationContext applicationContext) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(rcsDataSource);
        sessionFactory.setMapperLocations(applicationContext.getResources("classpath*:cn/xinfei/xdecision/common/migrate/*Mapper.xml"));
        sessionFactory.setTypeAliasesPackage("cn.xinfei.xdecision.common.migrate");
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sessionFactory.setConfiguration(configuration);

        return sessionFactory;
    }

    @Bean("rcsTransactionManager")
    @ConditionalOnProperty("spring.datasource.druid.rcs.enable")
    public DataSourceTransactionManager rcsTransactionManager(@Qualifier("rcsDataSource") DataSource rcsDataSource) {
        return new DataSourceTransactionManager(rcsDataSource);
    }


}